<?php
class App_Track extends Data_Item
{
    public function __construct($trackId = NULL)
    {
        $this->_commTableName = 'mod_track';
        $this->_commPrimaryKey = 'id';
        $this->_trackId = (int) $trackId;
        $this->_nid     = $this->_trackId;
    }

    // 路线详情
    public function detail ($trackId = NULL)
    {
        // 路线信息
        $trackId = $trackId > 0 ? $trackId : $this->_trackId;
        $detail  = parent::detail($trackId);
        $detail['images'] = explode('|', Arr::get($detail, 'images'));

        // 导游信息
        $guider  = new Guider(Arr::get($detail, 'uid'));
        $detail['guider'] = $guider->getUserInfo();

        return $detail;
    }

    // 日程
    public function days ($trackId = NULL)
    {
        $trackId = $trackId > 0 ? $trackId : $this->_trackId;

        $query = DB::select('d.dayNo', 'd.timeStart', 'd.timeStop', 'd.desc', 'b.*')
            ->from(array('mod_scenic_spot', 'b'))
            ->join(array('mod_track_days', 'd'), 'LEFT')
            ->on('b.id', '=', 'd.scenicId')
            ->where('d.trackId', '=', $trackId)
            ->order_by('d.dayNo', 'asc')
            ->order_by('d.timeStart', 'asc')
            ->execute();

        return $query->as_array();
    }

    // 获取路线下的景点ID
    public function getScenicIds ()
    {
        $query = DB::select('scenicId')
            ->from('mod_track_days')
            ->where('trackId', '=', $this->_trackId)
            ->execute()->as_array();

//         $ids = array();
//         foreach ($query as $rs)
//         {
//             $ids[] = $rs['scenicId'];
//         }

        return $query;
    }

    // 按天返回路线下的景点数据组信息
    public function scenicListByDay ()
    {
        $days  = $this->getDays();
        if (empty($days))
            $days = 5;

        $query = DB::select('a.*', 'b.name', 'b.type', 'b.subTitle', 'b.iconUrl')
            ->from(array('mod_scenic_spot', 'b'))
            ->join(array('mod_track_days', 'a'), 'LEFT')
            ->on('a.scenicId', '=', 'b.id')
            ->where('a.trackId', '=', $this->_trackId)
            ->order_by('timeStart','asc')
            ->execute();

        $ret = array();
        foreach ($query as $rs)
        {
            $dayNo = $rs['dayNo'];
            if (! isset($ret[$dayNo]))
            {
                $ret[$dayNo] = array();
            }

            $rs['jsonValue'] = json_encode(array(
                'startTime' => date("H:i", strtotime($rs['timeStart'])),
                'stopTime'  => date("H:i", strtotime($rs['timeStop'])),
                'desc'      => $rs['desc'],
            ));
            $ret[$dayNo][] = $rs;
        }

        for ($dayIndex = 1; $dayIndex <= $days; ++$dayIndex)
        {
            if (! isset($ret[$dayIndex]))
                $ret[$dayIndex] = array();
        }

        ksort($ret);
        return $ret;
    }

    // 删除路线
    public function remove ($trackId = NULL)
    {
        $trackId = $trackId > 0 ? $trackId : $this->_trackId;
        $this->update(array(
            'changed' => DB::expr('unix_timestamp(now())'),
            'status'  => 'INVALID',
        ), array('id', '=', $trackId));
    }

    // 路线搜索
    public function search ($guiderUid = NULL, $offset = 0, $limit = 10)
    {
        $count = DB::select(array('count("id")', 'counts'))
            ->from('mod_track')
            ->where('status', '=', 'VALID');
            
        $query = DB::select()
            ->from('mod_track')
            ->where('status', '=', 'VALID');


        if ($limit > 0)
        {
            $query->offset($offset)->limit($limit);
        }

        if ($guiderUid > 0)
        {
            $count->where('uid', '=', $guiderUid);
            $query->where('uid', '=', $guiderUid);
        }

        $counts = $count->execute()->get('counts');
        $query  = $query->execute();

        $tracks = array();
        foreach ($query as $rs)
        {
            $guider = new Guider($rs['uid']);
            $rs['guider'] = $guider->getUserInfo();
            $tracks[] = $rs;
        }

        return array($counts, $tracks);
    }

    // 更新路线的预定订单数量
    // 状态为1, 3, 7, 99是有效订单
    public function updateCountsOrders ($n = NULL)
    {
        // $n 参数作废

        // 获取实际订单数
        $counts = DB::select(array('count("id")', 'counts'))
            ->from('app_order')
            ->where('goodsType', '=', 'TRACK')
            ->where('goodsId', '=', $this->_trackId)
            ->where('status', 'in', array(1, 3, 7, 99))
            ->execute()
            ->get('counts');

        DB::update('mod_track')
            ->set(array('orders' => $counts))
            ->where('id', '=', $this->_trackId)
            ->execute();
    }

    public function getGuiderUid ()
    {
        return $this->getByKey('uid');
    }

    public function getMoney ($startDay, $stopDay, $persons)
    {
        $days    = $this->getByKey('days');
        $priceService = $this->getByKey('priceService');
        $priceOther   = $this->getByKey('priceOther');
        $priceFood    = $this->getByKey('priceFood');
        $priceTraffic = $this->getByKey('priceTraffic');
        $priceTicket  = $this->getByKey('priceTicket');

        $priceTrack = $priceFood + $priceTraffic + $priceTicket + $priceOther;
        //return $days * ($priceService + $priceTrack * $persons);
        return ($priceService + $priceTrack * $persons)*1.1;
    }

    public function getPrice ($humanRead = FALSE, $alldays = TRUE)
    {
        $perDay  = $this->getByKey('priceTotal');
        $days    = $this->getByKey('days');

        if ($alldays)
            $n = $days * $perDay;
        else
            $n = $perDay;

        if ($humanRead)
            return number_format($n / 100, 2);
        else
            return $n;
    }

    public function getName ()
    {
        return $this->getByKey('name');
    }

    public function getDays ()
    {
        return $this->getByKey('days');
    }

    public function getCurrentGuiderFreeDays ()
    {
        $freeDays = $this->getByKey('freetimeDays');
        $freeDays = explode(',', $freeDays);
        $days     = array();
        $today    = strtotime(date("Y-m-d"));
        foreach ($freeDays as $d)
        {
            $d = trim($d);
            if (! empty($d) && strtotime($d) >= $today)
                $days[] = $d;
        }

        

        $query = DB::select('startDay', 'stopDay')
            ->from('app_order')
            ->where('goodsType', '=', 'TRACK')
            ->where('goodsId', '=', $this->_trackId)
            ->where('status', '=', 3)
            ->execute();

        foreach ($query as $rs)
        {
            $t1 = strtotime($rs['startDay']);
            $t2 = strtotime($rs['stopDay']);
            if ($t1 >= $t2)
            {
                $t0 = $t1;
                $t1 = $t2;
                $t2 = $t0;
            }

            foreach ($days as $k => $day)
            {
                $t = strtotime($day);
                if ($t >= $t1 && $t <= $t2)
                    unset($days[$k]);
            }
        }

        return $days;
    }

    public function getByKey($key)
    {
        if (empty($this->_info))
        {
            $this->_info = DB::select()
                ->from('mod_track')
                ->where('id', '=', $this->_nid)
                ->execute()
                ->current();
        }

        return Arr::get($this->_info, $key);
    }
    

    public function getDaysService()
    {
        $item = $this->record($this->_trackId);
        $startDay = Arr::get($item, 'startDay');
        $stopDay  = Arr::get($item, 'stopDay');

        return (int) Arr::get($item, 'days');
    }

    // 判断用户是否可以申请第一次发布奖励
    public function canRequestSubmittedPrize ($uid)
    {
        $popu = new Popularize;
        if ($popu->userHasGotFirstSubmittedPrize($uid))
            return FALSE;
        else
            return TRUE;

        // DEBUG

        if ($this->isFirstSubmitted($uid))
        {
            $popu = new Popularize;
            if ($popu->userHasRequestFirstSubmittedPrize($uid))
                return FALSE;
            else
                return TRUE;
        }

        return FALSE;
    }


    // 判断是否是一个发布的路线
    public function isFirstSubmitted($uid)
    {
        $query = DB::select('id')
            ->from('mod_track')
            ->where('uid', '=', $uid)
            ->limit(1)
            ->order_by('created', 'asc')
            ->execute()
            ->get('id');

        $trackId = (int) $query;
        if ($trackId > 0 && $trackId == $this->_trackId)
            return TRUE;
        else
            return FALSE;
    }
}
